package middleware

import (
	"encoding/base64"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gofrs/uuid"
	"iot-base/auth/logger"
	"iot-base/common/jwt"
	"net/http"
	"strings"
	"time"
)

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		if c.Request.URL == nil || len(method) < 3 {
			return
		}
		origin := c.Request.Header.Get("Origin") //请求头部
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", origin)
			c.Request.Header.Del("Origin")
		} else {
			c.Header("Access-Control-Allow-Origin", "*")
		}
		//c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Credentials", "true")
		c.Header("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
		//允许跨域设置可以返回其他子段，可以自定义字段
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token,Authorization,Token,authToken,refreshToken")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		//c.Header("Access-Control-Allow-Credentials", "false")  //  跨域请求是否需要带cookie信息 默认设置为true
		c.Set("content-type", "application/json") // 设置默认返回格式是json
		// 放行 OPTIONS
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		//开始时间
		startTime := time.Now()
		requestId, _ := uuid.NewV4()
		//请求路由
		reqUrl := c.Request.RequestURI
		//请求方式
		reqMethod := c.Request.Method
		//请求ip
		clientIP := c.ClientIP()
		c.Set("RequestId", requestId.String())
		// req_params:[%s]
		logger.Log.Infof("RequestId:[%v],req_method:[%v],req_uri:[%v],clientIP:[%v]", requestId, reqMethod, reqUrl, clientIP)
		c.Next()
		//结束时间
		endTime := time.Now()
		// 执行时间
		latencyTime := endTime.Sub(startTime)
		// 日志格式
		logger.Log.Infof("RequestId:[%v],latency_time:[%v],", requestId, latencyTime)
	}
}

// refreshToken 刷新token.
func refreshToken(token string) string {
	if token == "" {
		return ""
	}
	// 截取字符串
	dataInfo := strings.Split(token, ".")
	decodeBytes, err := base64.RawStdEncoding.DecodeString(dataInfo[1])
	if err != nil {
		return ""
	}
	var custom jwt.CustomClaims
	err = json.Unmarshal(decodeBytes, &custom)
	if err != nil {
		return ""
	}
	//
	timeNow := time.Now().Unix()
	if timeNow-custom.Cat > 3600 {
		// 重新生产token
		var reToken string
		reToken, err = jwt.NewJWT().RefreshToken(token, time.Now().Add(time.Hour*2).Unix())
		if err != nil {
			return ""
		}
		return reToken
	}
	return ""
}
